//
//  PersonalViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/19.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class PersonalViewController: BaseUIViewController {
    
    let nameLabel = UILabel()
    let scoreLabel = UILabel()
    let dataArray = BehaviorRelay<[(key: String, value: String)]>.init(value: [])
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "江苏新源".localized
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: AppIcon.image("", size: 22, color: .white), style: .plain, target: self, action: #selector(setting))
        
        let imageHeight = SCREEN_WIDTH * 0.69
        UIImageView().config
            .image(#imageLiteral(resourceName: "personal_background"))
            .addTo(view)
            .makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(-imageHeight + UIApplication.shared.statusBarHeight + 140)
                make.height.equalTo(SCREEN_WIDTH * 0.69)
        }
        
        let foregroundView = UIView().config
            .backgroundColor(.white)
            .cornerRadius(5)
            .shadowColor(.black)
            .shadowRadius(10)
            .shadowOffset(.zero)
            .shadowOpacity(0.1)
            .addTo(view)
            .makeConstraints { (make) in
                make.left.equalTo(23)
                make.centerX.equalToSuperview()
                make.top.equalTo(UIApplication.shared.statusBarHeight + navigationBarHeight + 15)
                make.height.equalTo(150)
            }.view
        
        let foregroundImage = UIImageView().config
            .image(#imageLiteral(resourceName: "personal_foreground_image"))
            .cornerRadius(5)
            .clipsToBounds(true)
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.bottom.left.right.equalToSuperview()
                make.height.equalTo(41)
            }.view
        
        let shareButton = UIButton().config
            .backgroundImage(#imageLiteral(resourceName: "personal_share_image"))
            .title("分享领积分".localized)
            .image(UIDevice.current.isZhHans ? nil : AppIcon.image("", size: 15, color: .white))
            .imageEdgeInsets(UIDevice.current.isZhHans ? .zero : UIEdgeInsets.init(top: 0, left: -5, bottom: 0, right: 5))
            .titleColor(.white)
            .addTarget(self, action: #selector(share))
            .font(UIFont.systemFont(ofSize: 14, weight: .medium))
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.right.equalTo(0)
                make.top.equalTo(12)
                make.width.equalTo(UIDevice.current.isZhHans ? 88 : 145)
                make.height.equalTo(24)
        }.view
        
        nameLabel.config
            .font(UIFont.systemFont(ofSize: 14, weight: .bold))
            .textColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1))
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.left.equalTo(12)
                make.centerY.equalTo(shareButton.snp.centerY)
                make.right.equalTo(shareButton.snp.left).offset(-10)
            }
        
        scoreLabel.config
            .text("0")
            .textColor(APPConfig.baseColor)
            .font(UIFont.systemFont(ofSize: 36, weight: .regular))
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.centerY.equalTo(foregroundView.snp.centerY).offset(-4)
        }
        
        let pre = "我的积分".localized
        let attr = NSMutableAttributedString.init(string: "\(pre)")
        attr.setTextColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), text: pre)
        attr.setTextFont(UIFont.systemFont(ofSize: 12, weight: .bold), text: pre)
        attr.setParagraphSpace(6, alignment: .center)
        
        UILabel().config
            .numberOfLines(0)
            .textAlignment(.center)
            .font(.systemFont(ofSize: 12, weight: .medium))
            .textColor(#colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1))
            .attributedText(attr)
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.centerY.equalTo(foregroundImage.snp.top).offset(3)
        }
        
        let tableView = UITableView.init(frame: .zero, style: .plain).config
            .bounces(false)
            .cornerRadius(15)
            .estimatedRowHeight(0)
            .rowHeight(50)
            .register(PersonalCell.self)
            .separatorStyle(.none)
            .addTo(view)
            .makeConstraints { (make) in
                make.left.bottom.right.equalToSuperview()
                make.top.equalTo(foregroundView.snp.bottom).offset(20)
            }.view
        
        dataArray.asObservable()
            .bind(to: tableView.rx.items(cellType: PersonalCell.self)) { (_, model, cell) in
                cell.textLabel?.text = "  " + model.key
                cell.detailTextLabel?.text = model.value + "  "
            }.disposed(by: rx.disposeBag)
        
        let tableFooterView = UIView().config
            .frame(x: 0, y: 0, width: SCREEN_WIDTH, height: 130)
            .backgroundColor(.clear)
            .view
        
        tableView.tableFooterView = tableFooterView
        
        UIButton().config
            .backgroundImage(UIImage.imageWithColor(APPConfig.baseColor))
            .titleColor(.white)
            .clipsToBounds(true)
            .cornerRadius(5)
            .title("退出登录".localized)
            .addTarget(self, action: #selector(exitButtonClick))
            .addTo(tableFooterView)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.bottom.equalTo(-30)
                make.left.equalTo(40)
                make.height.equalTo(50)
            }
        
        ApiManager.userInfo().loadCache()
            .dataModelMap(PersonalModel.self)
            .catchErrorJustReturn(PersonalModel())
            .repeatWhen(Observable.merge(
                NotificationCenter.default.rx.notification(.userInfoRefresh).map{_ in},
                self.rx.viewWillAppear.asObservable().skip(1).map{_ in}
            )).startWith(PersonalModel())
            .subscribe(onNext: { [weak self] (model) in
                let dataArray =
                    [(key: "国家".localized, value: model.country),
                     (key: "姓名".localized, value: model.name),
                     (key: "电话".localized, value: model.phone),
                     (key: "职位".localized, value: model.position.count > 0 ? model.position : "未填".localized),
                     (key: "邮箱".localized, value: model.email),
                     (key: "公司名称".localized, value: model.companyName.count > 0 ? model.companyName : "未填".localized),
                     (key: "公司网站".localized, value: model.companyWebsite.count > 0 ? model.companyWebsite : "未填".localized),
                     (key: "备注".localized, value: model.remarks.count > 0 ? model.remarks : "未填".localized)]
                self?.dataArray.accept(dataArray)
                self?.nameLabel.text = model.name
                self?.scoreLabel.text = model.scoreNum
        }).disposed(by: rx.disposeBag)
    }
    
    @objc func exitButtonClick() {
        let alert = UIAlertController.init(title: "系统提示".localized, message: "确定要退出登录吗？".localized, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "取消".localized, style: .cancel, handler: nil))
        alert.addAction(UIAlertAction.init(title: "确定".localized, style: .destructive, handler: { (_) in
            APPUser.shared.logOut {
                let vc = MainNavigationViewController.init(rootViewController: LoginViewController(type: .login))
                UIApplication.shared.keyWindow?.setRootViewController(vc, type: .push)
            }
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    @objc func share() {
        
        /*
        let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        let weixinFriend = UIAlertAction(title: "微信好友", style: .default) { (action) in
            print("微信好友")
            EDSUtility.share(withTitle: "分享", desc: "", shareUrl: "https://www.baidu.com", shareType: 1)
        }
        let friendQian = UIAlertAction(title: "朋友圈", style: .default) { (action) in
            print("朋友圈")
            EDSUtility.share(withTitle: "分享", desc: "", shareUrl: "https://www.baidu.com", shareType: 2)
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
            print("用户点击取消")
        }
        alertVC.addAction(weixinFriend)
        alertVC.addAction(friendQian)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
        */
        
        
        ApiManager.getConfig().request()
            .map{ $0.jsonDictionary }
            .map{ $0.dictionaryValue("data").stringValue("apple_store") }
            .trackingLoading()
            .subscribe(onNext: { [weak self] (url) in
                let obj: Any
                if let diwnloadUrl = URL.init(string: url) {
                    obj = diwnloadUrl
                } else {
                    obj = url
                }
                let vc = UIActivityViewController.init(activityItems: [obj], applicationActivities: nil)
                vc.completionWithItemsHandler = { [weak self] _, success, _, _ in
                    guard let self = self else { return }
                    if success {
                        ApiManager.shareSuccess().request()
                            .post(.userInfoRefresh)
                            .subscribe()
                            .disposed(by: self.rx.disposeBag)
                    }
                }
                self?.present(vc, animated: true , completion: nil)
            }).disposed(by: rx.disposeBag)
        
    }
    
    @objc func setting() {
        self.navigationController?.pushViewController(SettingViewController(), animated: true)
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .clearColor
    }
    
}
